package thread_case;

class MyBlockingQueue1 {
    private String[] elems = null;
    private int head = 0;
    private int tail = 0;
    private int size = 0;
    private Object locker = new Object();


    public MyBlockingQueue1(int len) {
        elems = new String[len];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= elems.length) {
                locker.wait();
            }
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (locker) {
            while (size == 0) {
                locker.wait();
            }
            String ret = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}

public class ThreadDemo3 {
    public static void main(String[] args) {
        MyBlockingQueue1 myBlockingQueue = new MyBlockingQueue1(100);
        Thread t1 = new Thread(()->{
            Integer n = 0;
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    myBlockingQueue.put(n.toString());
                    System.out.println("生产元素:->" + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                n++;
            }
        });
        Thread t2 = new Thread(()->{
            while (true) {
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    System.out.println("取出元素:" + myBlockingQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
